package org.red5.acs.dataManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.red5.acs.Application;
import org.red5.acs.dataSet.User;
import org.red5.acs.dataSet.soRoom;
import org.red5.server.api.IClient;
import org.red5.server.api.IConnection;
import org.red5.server.api.Red5;

public class soRoomManager {
	private Application mainApplication;
	private ArrayList<soRoom> rooms = new ArrayList<soRoom>();

	public void setApp(Application _app) {
		try{
			mainApplication = _app;
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public void joinSo(String soName)
	{
		IConnection conn = Red5.getConnectionLocal();		
		IClient client = conn.getClient();
		try{
			soRoom tRoom = findRoom(soName);
			
			System.out.println("joinSo::"+soName);
			
			if(tRoom==null){
				tRoom = new soRoom();	
				tRoom.soName = soName;				
				addRoom(tRoom);
			}
			
			User u = mainApplication.getUserManager().findUserOfId(client.getId());
			
			u.currentRoom = soName;
			
			System.out.println(u.userName+" add the room "+u.currentRoom+":"+soName);
			
			tRoom.soOnlines.add(u);
			
			app.getAdminManager().getOnlinesInfo();
			
		}catch (Exception e) {
			System.out.println("joinSo error");
			e.printStackTrace();
		}
		//users.add(u);
		//userConn.put(u.id, conn);
	}
	
	public void onUserDisConnect(User u){
		Map<String,Object> re = new HashMap<String,Object>();
		re.put("functionName", "userLeft");	
		
		try{
			soRoom tRoom = findRoom(u.currentRoom);
			System.out.println("layOutRoom "+u.currentRoom);
			if(tRoom==null){
				return;
			}
			
			re.put("success", "true");
			//re.put("data", tRoom.soOnlines);
			re.put("data", u);
			
			tRoom.removeUserFromRoom(client.getId());
			
			
			mainApplication.getCommandToClient().soLnvoke("serverReturn", u.currentRoom,re);
			
		}catch (Exception e) {
			re.put("success", "false");
			System.out.println("layOutRoom error");
		}
	}
	
	public void addRoom(soRoom newRoom){
		try{			
			rooms.add(newRoom);
		}catch(Exception e){
			System.out.println("addRoom error");
		}
	}
	
	public soRoom findRoom(String RoomName){
		try{
			int length = rooms.size();  
			for(int i = 0; i < length; i++)
			{
				if(rooms.get(i).soName.equals(RoomName)){
					return rooms.get(i);
				}
			}
		}catch(Exception e){
			System.out.println("findRoom error");
			return null;
			//e.printStackTrace();			
		}
		return null;
	}
	
	
	
	public int getOnlineCount(String soName)
	{		
		try{
			soRoom tRoom = findRoom(soName);
			
			if(tRoom==null){
				tRoom = new soRoom();	
				tRoom.soName = soName;				
				addRoom(tRoom);
				return 0;
			}			
			return tRoom.soOnlines.size();
		}catch (Exception e) {
			System.out.println("joinSo error");
			e.printStackTrace();
			return 0;
		}
	}
}
